{% extends 'base.html' %}
{% load static %}
{% load i18n %}

{% block title %}{{ page_title }} - {{ block.super }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="p-5 mb-4 bg-light rounded-3">
      <div class="container-fluid py-5">
        <h1 class="display-5 fw-bold">{% blocktrans with user_name=user.username %}欢迎, {{ user_name }}!{% endblocktrans %}</h1>
        <p class="col-md-8 fs-4">{% trans "欢迎使用水稻种植管理系统。管理您的田块和记录，查看数据分析。" %}</p>
         {# Quick Links moved to a row below #}
      </div>
    </div>

    {# Quick Stats/Links Row #}
    <div class="row mb-4 g-3">
        <div class="col-md-4">
             <div class="card text-center h-100">
                 <div class="card-body">
                     <h5 class="card-title"><i class="bi bi-map text-success"></i> {% trans "总田块数" %}</h5>
                     <p class="card-text fs-3 fw-bold">{{ total_fields|default:0 }}</p>
                     <a href="{% url 'field_management:field_list' %}" class="btn btn-sm btn-outline-success">{% trans "管理田块" %}</a>
                     <a href="{% url 'field_management:field_add' %}" class="btn btn-sm btn-success"><i class="bi bi-plus-lg"></i> {% trans "添加" %}</a>
                 </div>
             </div>
        </div>
         <div class="col-md-4">
             <div class="card text-center h-100">
                 <div class="card-body">
                     <h5 class="card-title"><i class="bi bi-calendar-check text-primary"></i> {% trans "总种植记录" %}</h5>
                     <p class="card-text fs-3 fw-bold">{{ total_records|default:0 }}</p>
                     <a href="{% url 'planting_records:record_list' %}" class="btn btn-sm btn-outline-primary">{% trans "查看记录" %}</a>
                     <a href="{% url 'planting_records:record_add' %}" class="btn btn-sm btn-primary"><i class="bi bi-plus-lg"></i> {% trans "添加" %}</a>
                 </div>
             </div>
        </div>
         <div class="col-md-4">
              {# Placeholder for another quick stat/link #}
              <div class="card text-center h-100">
                 <div class="card-body">
                     <h5 class="card-title"><i class="bi bi-graph-up text-info"></i> {% trans "更多分析" %}</h5>
                     <p class="card-text fs-3 fw-bold">...</p>
                     <a href="#" class="btn btn-sm btn-outline-info">{% trans "查看报告" %}</a>
                 </div>
             </div>
         </div>
    </div>


    {# Charts Row #}
    <div class="row g-4">
        <div class="col-lg-6">
            <div class="card shadow-sm h-100">
                <div class="card-header">
                    <i class="bi bi-pie-chart-fill me-2"></i> {% trans "各品种种植面积占比 (亩)" %}
                </div>
                <div class="card-body" style="min-height: 350px; display: flex; justify-content: center; align-items: center;">
                     {# Add a check if data exists #}
                    {% if variety_area_labels_json and variety_area_labels_json != '[]' %}
                         <canvas id="varietyAreaChart"></canvas>
                    {% else %}
                         <p class="text-muted">{% trans "暂无足够数据生成图表。" %}</p>
                    {% endif %}
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card shadow-sm h-100">
                <div class="card-header">
                    <i class="bi bi-bar-chart-line-fill me-2"></i> {% trans "每月种植记录数量" %}
                </div>
                <div class="card-body" style="min-height: 350px;">
                     {% if planting_month_labels_json and planting_month_labels_json != '[]' %}
                        <canvas id="plantingsPerMonthChart"></canvas>
                     {% else %}
                         <p class="text-muted">{% trans "暂无足够数据生成图表。" %}</p>
                     {% endif %}
                </div>
            </div>
        </div>
    </div>

</div> {# End container #}
{% endblock %}


{% block extra_js %}
{# Include Chart.js library #}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>

{# Chart Initialization Script #}
<script>
    document.addEventListener('DOMContentLoaded', function() {

        // --- Variety Area Chart (Pie) ---
        const varietyCanvas = document.getElementById('varietyAreaChart');
        if (varietyCanvas) { // Check if canvas exists
            try {
                const varietyLabels = JSON.parse('{{ variety_area_labels_json|escapejs }}');
                const varietyData = JSON.parse('{{ variety_area_data_json|escapejs }}');

                if (varietyLabels.length > 0) {
                    new Chart(varietyCanvas, {
                        type: 'pie', // Or 'doughnut'
                        data: {
                            labels: varietyLabels,
                            datasets: [{
                                label: '{% trans "种植面积 (亩)" %}',
                                data: varietyData,
                                backgroundColor: [ // Add more colors if needed
                                    'rgba(25, 135, 84, 0.7)', // Primary green
                                    'rgba(255, 193, 7, 0.7)', // Yellow
                                    'rgba(13, 110, 253, 0.7)', // Blue
                                    'rgba(220, 53, 69, 0.7)', // Red
                                    'rgba(108, 117, 125, 0.7)', // Gray
                                    'rgba(255, 159, 64, 0.7)', // Orange
                                    'rgba(111, 66, 193, 0.7)', // Purple
                                ],
                                borderColor: [ // Optional border
                                    'rgba(255, 255, 255, 1)',
                                ],
                                borderWidth: 1
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false, // Allow flexible sizing
                            plugins: {
                                legend: {
                                    position: 'top', // Or 'bottom', 'left', 'right'
                                },
                                tooltip: {
                                    callbacks: {
                                        label: function(context) {
                                            let label = context.label || '';
                                            if (label) {
                                                label += ': ';
                                            }
                                            if (context.parsed !== null) {
                                                // Format number with commas and units
                                                label += context.parsed.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' {% trans "亩" %}';
                                            }
                                            return label;
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            } catch (e) {
                console.error("Error parsing chart data (Variety Area):", e);
                varietyCanvas.parentElement.innerHTML = '<p class="text-danger">无法加载品种面积图表数据。</p>';
            }
        } // end if varietyCanvas

        // --- Plantings per Month Chart (Bar) ---
        const monthCanvas = document.getElementById('plantingsPerMonthChart');
         if (monthCanvas) { // Check if canvas exists
            try {
                const monthLabels = JSON.parse('{{ planting_month_labels_json|escapejs }}');
                const monthData = JSON.parse('{{ planting_month_data_json|escapejs }}');

                 if (monthLabels.length > 0) {
                    new Chart(monthCanvas, {
                        type: 'bar', // Or 'line'
                        data: {
                            labels: monthLabels,
                            datasets: [{
                                label: '{% trans "种植记录数量" %}',
                                data: monthData,
                                backgroundColor: 'rgba(25, 135, 84, 0.6)', // Semi-transparent green
                                borderColor: 'rgba(25, 135, 84, 1)',
                                borderWidth: 1,
                                barPercentage: 0.6, // Make bars slightly thinner
                                categoryPercentage: 0.8
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        // Ensure only integers are shown on y-axis for counts
                                        stepSize: 1
                                    }
                                },
                                x: {
                                     grid: {
                                         display: false // Hide vertical grid lines
                                     }
                                }
                            },
                            plugins: {
                                legend: {
                                    display: false // Hide legend if only one dataset
                                },
                                 tooltip: {
                                    callbacks: {
                                        title: function(tooltipItems) {
                                            // Show month name in tooltip title
                                            return tooltipItems[0].label;
                                        },
                                         label: function(context) {
                                            let label = context.dataset.label || '';
                                            if (label) {
                                                label += ': ';
                                            }
                                            if (context.parsed.y !== null) {
                                                label += context.parsed.y;
                                            }
                                            return label;
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            } catch (e) {
                console.error("Error parsing chart data (Plantings per Month):", e);
                monthCanvas.parentElement.innerHTML = '<p class="text-danger">无法加载月度种植图表数据。</p>';
            }
        } // end if monthCanvas

    }); // End DOMContentLoaded
</script>
{% endblock %}